package com.rongshu.view.home.activity;

import android.animation.Animator;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.rongshu.App;
import com.rongshu.R;
import com.rongshu.eventbus.AddAttention;
import com.rongshu.eventbus.AttentionStateChange;
import com.rongshu.eventbus.ChangeTextSize;
import com.rongshu.eventbus.CleanCommentEphemeralData;
import com.rongshu.eventbus.CleanKeyBoard;
import com.rongshu.eventbus.HeaderClick;
import com.rongshu.eventbus.PlatformToShare;
import com.rongshu.eventbus.PostComment;
import com.rongshu.eventbus.ReceiverScreenEvent;
import com.rongshu.eventbus.ScrollToCommentDistrict;
import com.rongshu.eventbus.SetInput;
import com.rongshu.eventbus.UpdateCommmentCount;
import com.rongshu.utils.AnimationUtil;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.LoginUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.discovery.bean.AuthorDetailBean;
import com.rongshu.view.home.adapter.pageradapter.ArticleDetailsPagerAdapter;
import com.rongshu.view.home.contract.MoreArticleDetailView;
import com.rongshu.view.home.entity.ArticleAttribute;
import com.rongshu.view.home.entity.ArticleItem;
import com.rongshu.view.home.entity.ArticleLike;
import com.rongshu.view.home.entity.UserCollect;
import com.rongshu.view.home.fragment.dialog.InputNoteDialog;
import com.rongshu.view.home.fragment.dialog.MultifunctionDialog;
import com.rongshu.view.home.presenter.MoreArticleDetailsPresenter;
import com.rongshu.view.home.widget.FontSizeView;
import com.rongshu.view.home.widget.favor.FavorLayout;
import com.rongshu.view.userInfo.activity.ToReportActivity;
import com.umeng.socialize.UMShareAPI;
import com.utils.DensityUtil;
import com.utils.FastClickUtils;
import com.utils.SPUtils;
import com.utils.constants.SPKey;
import com.widget.CircleImageView;
import com.widget.loading.AnimatorListener;
import com.widget.stretch.OnStretchListener;
import com.widget.stretch.StretchPager;
import com.widget.titlebar.ImmersionBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;

import static com.rongshu.utils.UserInfoUtils.getUserId;

public class MoreArticleDetailsActivity extends BaseActivity<MoreArticleDetailsPresenter> implements MoreArticleDetailView, OnStretchListener {
    @BindView(R.id.layout_parent)
    RelativeLayout layout_parent;
    @BindView(R.id.layout_top_menu)
    LinearLayout layout_top_menu;
    @BindView(R.id.layout_top_head)
    RelativeLayout layout_top_head;
    @BindView(R.id.iv_head_icon)
    CircleImageView iv_head_icon;
    @BindView(R.id.iv_vip)
    ImageView iv_vip;
    @BindView(R.id.txt_article_author)
    TextView txt_article_author;
    @BindView(R.id.layout_add_attention)
    RelativeLayout layout_add_attention;
    @BindView(R.id.line)
    View line;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.iv_like)
    ImageView iv_like;
    @BindView(R.id.txt_like)
    TextView txt_like;
    @BindView(R.id.txt_comment)
    TextView txt_comment;
    @BindView(R.id.viewPager)
    StretchPager viewPager;

    //pageIndex
    private int pageIndex = 1;
    //pageSize
    private int pageSize = 10;
    //map
    private Map<String, Object> map = null;
    //intent
    private Intent intent = null;
    //list
    private List<ArticleItem> mArticleItemList = null;
    //当前文章所在的位置
    private int currentPosition = 0;
    //current item
    private ArticleItem articleItem = null;
    //current attribute
    private ArticleAttribute.ResponseBean attribute = null;
    //adapter
    private ArticleDetailsPagerAdapter mArticleDetailsPagerAdapter = null;
    //刚进来时间记录
    private long firstTime = 0;
    //toolbarHeight
    private int toolbarHeight;
    //scrollY
    private int mScrollY = 0;
    //标题位置
    private int mTitleLocation = 0;
    //是否在最顶部
    private boolean isScrollTheTop = true;
    //是否已经出现了top上的头像，关注信息
    private boolean isShowAttention = false;
    //是否滑动到了评论区域
    private boolean isScrollToComment = false;
    //是否手动点赞
    private boolean isManualLike = false;
    //点赞爱心
    private FavorLayout favorLayout = null;
    //点赞提示语
    private List<String> likeTips = null;
    //request
    public static final int REQUEST_LOGIN = 0X0A;

    //distance
    static final int Distance = (int) (Resources.getSystem().getDisplayMetrics().density * 80 + 0.5);
    // viewpager left right
    private View leftView, rightView;
    //refresh,loading anim
    private RotateAnimation animLeftStart, animLeftEnd, animRightStart, animRightEnd;
    //status
    private int lastStatus = 0;
    //已记载全部
    private boolean isLoadAll = false;
    //direction
    private int direction = -1;

    //dialog
    private InputNoteDialog inputNoteDialog = null;
    //内容
    private String mContent = "";
    //提示
    private String mReplyContent = null;
    //@的用戶信息
    private LinkedHashMap<String, AuthorDetailBean> authorDetailBeanMap = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hintTitleBar();
        ImmersionBar.with(this).keyboardEnable(false,
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
                .init();
        EventBus.getDefault().register(this);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_more_article_details_view;
    }

    @Override
    protected void initView() {
        //presenter
        setPresenter(new MoreArticleDetailsPresenter(this), this);
        //intent
        intent = getIntent();
        if (intent == null) {
            return;
        }
        pageIndex = intent.getIntExtra(Constant.INTENT_PAGEINDEX, pageIndex);
        currentPosition = intent.getIntExtra(Constant.INTENT_POSITION, currentPosition);
        mArticleItemList = App.getApplication().getList();
        //margin
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_top_menu.getLayoutParams();
        toolbarHeight = DensityUtil.getStateBar(this);
        layoutParams.height = toolbarHeight + getResources().getDimensionPixelSize(R.dimen.dd_dimen_91px);
        layout_top_menu.setLayoutParams(layoutParams);
        layout_top_menu.setPadding(0, toolbarHeight, 0, 0);
        layout_top_menu.setBackgroundColor(getResources().getColor(R.color.white));
        //list
        likeTips = Arrays.asList(new String[]{
                getString(R.string.its_nice_to_be_liked),
                getString(R.string.received_your_like_thank_you),
                getString(R.string.once_thumb_up_very_close),
                getString(R.string.warm_praise_reliable_shoulder),
                getString(R.string.thanks_for_your_encouragement)});
        //anim rotate
        animLeftStart = new RotateAnimation(0f, -180f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animLeftEnd = new RotateAnimation(-180f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animRightStart = new RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animRightEnd = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        //left
        animLeftStart.setFillAfter(true);
        animLeftStart.setDuration(300);
        animLeftEnd.setDuration(300);
        //right
        animRightStart.setFillAfter(true);
        animRightStart.setDuration(300);
        animRightEnd.setDuration(300);
        //left,right view
        leftView = LayoutInflater.from(this).inflate(R.layout.item_pager_left, null);
        rightView = LayoutInflater.from(this).inflate(R.layout.item_pager_right, null);
        //adapter
        mArticleDetailsPagerAdapter = new ArticleDetailsPagerAdapter(getSupportFragmentManager());
        mArticleDetailsPagerAdapter.setResponseBeanList(mArticleItemList);
        //pager
        viewPager.setRefreshView(leftView, rightView);
        viewPager.setOnStretchListener(this);
        viewPager.setAdapter(mArticleDetailsPagerAdapter);
        viewPager.setCurrentItem(currentPosition);
        viewPager.setPageMargin(getResources().getDimensionPixelOffset(R.dimen.dd_dimen_2px));
        viewPager.setPageMarginDrawable(R.drawable.shape_pager_magin_bg);
        //记录第一次进来的时间
        firstTime = System.currentTimeMillis();
        //map
        authorDetailBeanMap = new LinkedHashMap<>();
        //记录当前位置文章信息
        recordCurrentArticle();
        //pagechange listener
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int position) {
                if (currentPosition == position) {
                    return;
                }
                mContent = "";
                mReplyContent = null;
                authorDetailBeanMap = new LinkedHashMap<>();
                isScrollToComment = false;
                isScrollTheTop = true;
                isShowAttention = false;
                mScrollY = 0;
                mTitleLocation = 0;
                layout_top_head.setVisibility(View.GONE);
                layout_add_attention.setVisibility(View.GONE);
                inputNoteDialog = null;
                //键盘，输入框，@信息，提示语以及通知清空数据
                EventBus.getDefault().post(new CleanCommentEphemeralData());
                //更新集合中数据
                mArticleItemList.set(currentPosition, articleItem);
                //统计用户离开上一页的行为
                statisticsPreviousBehavior(currentPosition, position);
                //记录adapter位置和该位置文章详情
                currentPosition = position;
                //记录当前文章
                recordCurrentArticle();
                //如果滑动大于等于90%的页数了，自动请求下个10篇
                if (mArticleItemList != null) {
                    int count = mArticleItemList.size();
                    if ((currentPosition + 1) >= count * 0.8) {
                        direction = StretchPager.STRETCH_RIGHT;
                        pageIndex++;
                        getAtricleDetails();
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        //爱心
        favorLayout = new FavorLayout(this);
        RelativeLayout.LayoutParams lpFavor = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                getResources().getDimensionPixelOffset(R.dimen.dd_dimen_700px));
        lpFavor.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        lpFavor.bottomMargin = getResources().getDimensionPixelOffset(R.dimen.dd_dimen_32px);
        favorLayout.setLayoutParams(lpFavor);
        layout_parent.addView(favorLayout);
        //新手右边悬浮提示
        showViewpagerAnimation();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {
        //如果滑动大于等于90%的页数了，自动请求下个10篇
        if (mArticleItemList != null) {
            int count = mArticleItemList.size();
            if (currentPosition >= count * 0.8) {
                direction = StretchPager.STRETCH_RIGHT;
                pageIndex++;
                getAtricleDetails();
            }
        }
    }

    /**
     * viewpager首次新手引导动画
     */
    public void showViewpagerAnimation() {
        boolean firstFlipOver = SPUtils.getPreferences(SPKey.FIRST_FLIP_OVER, true);
        if (firstFlipOver) {
            TranslateAnimation translateAnimation = new TranslateAnimation(0f, -DensityUtil.getScreenWidth(this) / 8, 0, 0);
            translateAnimation.setDuration(500);
            translateAnimation.setInterpolator(new LinearInterpolator());
            translateAnimation.setRepeatMode(Animation.REVERSE);
            translateAnimation.setRepeatCount(3);
            viewPager.setAnimation(translateAnimation);
            translateAnimation.start();
            translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    SPUtils.putPreferences(SPKey.FIRST_FLIP_OVER, false);
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    showFirstGuide();
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
    }

    /**
     * 新手右边悬浮提示
     */
    private void showFirstGuide() {
        final View tipView = LayoutInflater.from(this).inflate(R.layout.new_hand_guide_right_tips_view, null);
        RelativeLayout.LayoutParams lpTip = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        ImageView iv_pair_arrow = tipView.findViewById(R.id.iv_pair_arrow);
        lpTip.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        lpTip.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        lpTip.bottomMargin = DensityUtil.getScreenHeight(this) / 3;
        tipView.setLayoutParams(lpTip);
        layout_parent.addView(tipView);
        //箭头动画
        final TranslateAnimation translateAnimation = new TranslateAnimation(0f, -10f, 0, 0);
        translateAnimation.setDuration(500);
        translateAnimation.setInterpolator(new LinearInterpolator());
        translateAnimation.setRepeatMode(Animation.REVERSE);
        translateAnimation.setRepeatCount(7);
        iv_pair_arrow.setAnimation(translateAnimation);
        translateAnimation.start();
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                layout_parent.removeView(tipView);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    /**
     * 请求文章
     */
    public void getAtricleDetails() {
        if (pageIndex == 1) {
            showLoading(true);
        }
        map = new HashMap<>();
        map.put("user_id", getUserId());
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        presenter.getArticleDetails(
                (int) map.get("user_id"),
                (int) map.get("pageIndex"),
                (int) map.get("pageSize"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 获取文章属性
     */
    private void getArticleAttribute() {
        int user_id = getUserId();
        if (articleItem == null) {
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("contribute_id", articleItem.getContribute_id());
        presenter.getArticleAttribute((int) map.get("user_id"),
                (int) map.get("contribute_id"),
                Common.encryptionSign(map));
    }

    /**
     * 离开文章时填写对文章的行为记录
     */
    private void getLogUserBehavior(int ScrollingPercentMax, int TotalStayTime) {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            return;
        }
        if (articleItem == null) {
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("contribute_id", articleItem.getContribute_id());
        map.put("ScrollingPercentMax", ScrollingPercentMax);
        map.put("TotalStayTime", TotalStayTime);
        presenter.getLogUserBehavior((int) map.get("user_id"),
                (int) map.get("contribute_id"),
                (int) map.get("ScrollingPercentMax"),
                (int) map.get("TotalStayTime"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 浏览
     */
    private void getbrowse() {
        //user_id
        int user_id = getUserId();
        if (articleItem == null) {
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("contribute_id", articleItem.getContribute_id());
        map.put("type", 1);
        map.put("code", "browse");
        presenter.getbrowse((int) map.get("user_id"),
                (int) map.get("contribute_id"),
                (int) map.get("type"),
                (String) map.get("code"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 获取我是否收藏
     */
    private void getIsShouChang() {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            return;
        }
        if (articleItem == null) {
            return;
        }

        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("contribute_id", articleItem.getContribute_id());
        map.put("type", 1);
        presenter.getIsShouChang((int) map.get("user_id"),
                (int) map.get("contribute_id"),
                (int) map.get("type"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 收藏
     */
    private void collectArticle() {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(this, REQUEST_LOGIN);
            return;
        }
        if (articleItem == null) {
            return;
        }
        //http
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("type", 1);//(1文章 2帖子)
        map.put("content_id", articleItem.getContribute_id());
        presenter.getIsCollect(
                (int) map.get("user_id"),
                (int) map.get("type"),
                (int) map.get("content_id"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 文章点赞/帖子点赞
     */
    public void getLike() {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(this, REQUEST_LOGIN);
            return;
        }
        if (articleItem == null) {
            return;
        }
        //id
        int id = articleItem.getContribute_id();
        //http
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("type", "article");//点赞类型(post帖子，article文章)
        presenter.getlike(
                id, (int) map.get("user_id"),
                (String) map.get("type"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 取消文章点赞
     */
    public void getOfflike() {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(this, REQUEST_LOGIN);
            return;
        }
        if (articleItem == null) {
            return;
        }
        //id
        int id = articleItem.getContribute_id();
        //http
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("type", "article");//点赞类型(post帖子，article文章)
        map.put("contribute_id", id);
        presenter.getOfflike(
                (int) map.get("user_id"),
                (String) map.get("type"),
                (int) map.get("contribute_id"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 上传前一篇文章的行为
     */
    private void statisticsPreviousBehavior(int lastItemPosition, int position) {
        if (lastItemPosition == position) {
            return;
        }
        //停留的时间
        int TotalStayTime = (int) ((System.currentTimeMillis() - firstTime) / 1000);
        getLogUserBehavior(0, TotalStayTime);
        //重新记录新文章进来的时间
        firstTime = System.currentTimeMillis();
    }

    /**
     * Toolbar背景，icon替换
     */
    private void replaceToolbarrResource(boolean isWhite) {
        if (mScrollY == 0) {
            layout_top_menu.getBackground().setAlpha(isWhite ? 255 : 0);
        } else {
            if (mScrollY <= mTitleLocation && !isWhite) {
                int alpha = (int) ((mScrollY / Float.valueOf(mTitleLocation)) * 255);
                layout_top_menu.getBackground().setAlpha(alpha);
            } else {
                layout_top_menu.getBackground().setAlpha(255);
            }
        }
        iv_back.setBackgroundResource(isWhite ? R.drawable.gray_left_menu
                : isScrollTheTop ? R.drawable.white_left_menu : R.drawable.gray_left_menu);
        line.setVisibility(isWhite ? isScrollTheTop ? View.GONE : View.VISIBLE :
                mScrollY > mTitleLocation ? View.VISIBLE : View.GONE);
        layout_top_head.setVisibility(isShowAttention ? View.VISIBLE : View.GONE);
        layout_add_attention.setVisibility(articleItem.getUser_id() == getUserId() ?
                View.GONE : articleItem.getIsConcern() > 0 ?
                View.GONE : isShowAttention ? View.VISIBLE : View.GONE);//0没有关注，1已关注
    }

    /**
     * 点赞，评论
     */
    private void updateArticleAttribute() {
        if (attribute == null) {
            return;
        }
        //赞
        final boolean isLike = attribute.getIsLike() == 0 ? false : true;
        final int likeCount = attribute.getLikeCount();
        setIv_like(isLike, likeCount);
        //评论
        int commentCount = attribute.getCommentCount();
        setCommentCount(commentCount);
    }

    /***
     *点赞数
     */
    private void setIv_like(boolean islike, int likeCount) {
        iv_like.setImageResource(islike ? R.drawable.love_red_icon : R.drawable.love_icon);
        if (islike && isManualLike) {
            isManualLike = false;
            favorLayout.addFavor();
            toast(likeTips.get(new Random().nextInt(likeTips.size())));
        }
        txt_like.setText(likeCount + "");
    }

    /**
     * 评论数
     */
    private void setCommentCount(int commentCount) {
        txt_comment.setText(commentCount + "");
    }

    /**
     * 记录当前位置的文章信息
     */
    private void recordCurrentArticle() {
        //记录当前第一个
        articleItem = mArticleItemList.get(currentPosition);
        //修改toolbar背景
        boolean isWhiteBg = TextUtils.isEmpty(articleItem.getTopImg()) ? true : false;
        replaceToolbarrResource(isWhiteBg);
        //头像
        RequestOptions options = new RequestOptions()
                .placeholder(R.drawable.user_head_icon);
        Glide.with(this)
                .load(articleItem.getAvatar())
                .apply(options)
                .into(iv_head_icon);
        //vip
        iv_vip.setVisibility(articleItem.isVip() ? View.VISIBLE : View.GONE);
        //作者
        txt_article_author.setText(articleItem.getBi_name());
        //获取文章属性
        getArticleAttribute();
        //获取我是否收藏
        getIsShouChang();
        //统计阅读
        getbrowse();
    }

    @OnClick({R.id.head_left, R.id.layout_function, R.id.layout_love, R.id.layout_comment, R.id.layout_share,
            R.id.txt_wrtie_note, R.id.layout_add_attention, R.id.iv_head_icon})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.head_left:
                onBackPressed();
                break;
            case R.id.layout_function://菜单
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                MultifunctionDialog.Builder builder = new MultifunctionDialog.Builder(this);
                builder.setIsCollect(articleItem.getIsCollect() == 0 ? false : true)
                        .setOnChangeCallbackListener(new FontSizeView.OnChangeCallbackListener() {
                            @Override
                            public void onChangeListener(int position) {
                                //获取是否保存过字体类型
                                final int fontType = SPUtils.getPreferences(SPKey.FONTPATTERN, 1);
                                if (fontType == position) {
                                    return;
                                }
                                SPUtils.putPreferences(SPKey.FONTPATTERN, position);
                                EventBus.getDefault().post(new ChangeTextSize(position));
                            }
                        })
                        .setOnCollectReportClickListener(new MultifunctionDialog.Builder.OnCollectReportClickListener() {
                            @Override
                            public void onCollectClick() {
                                if (FastClickUtils.isFastClick()) {
                                    return;
                                }
                                collectArticle();
                            }

                            @Override
                            public void onReportClick(Dialog dialog) {
                                if (FastClickUtils.isFastClick() && articleItem == null) {
                                    return;
                                }

                                if (getUserId() == 0) {
                                    LoginUtils.toLogin(MoreArticleDetailsActivity.this, REQUEST_LOGIN);
                                    return;
                                }

                                intent = new Intent(MoreArticleDetailsActivity.this, ToReportActivity.class);
                                intent.putExtra(Constant.INTENT_MESSAGE, articleItem.getContribute_id());
                                intent.putExtra(Constant.INTENT_TYPE, 3);
                                startActivity(intent);
                                dialog.dismiss();
                            }
                        }).create().show();
                break;
            case R.id.layout_love://赞
                if (FastClickUtils.isFastClick() || attribute == null) {
                    return;
                }

                boolean isLike = attribute.getIsLike() == 0 ? false : true;
                if (!isLike) {
                    isManualLike = true;
                    getLike();
                } else {
                    getOfflike();
                }
                break;
            case R.id.layout_comment://评论
                if (FastClickUtils.isFastClick() || attribute == null) {
                    return;
                }
                //评论记忆功能
                EventBus.getDefault().post(new ScrollToCommentDistrict());
                if (getUserId() != 0) {
                    int comment = attribute.getCommentCount();
                    if (comment == 0 && !isScrollToComment) {
                        getInputDialog().show(getSupportFragmentManager(), InputNoteDialog.class.getSimpleName());
                    }
                }
                break;
            case R.id.layout_share://分享
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                EventBus.getDefault().post(new PlatformToShare());
                break;
            case R.id.txt_wrtie_note://写留言
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                if (getUserId() == 0) {
                    LoginUtils.toLogin(this, REQUEST_LOGIN);
                    return;
                }
                getInputDialog().show(getSupportFragmentManager(), InputNoteDialog.class.getSimpleName());
                break;
            case R.id.iv_head_icon://头像
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                EventBus.getDefault().post(new HeaderClick());
                break;
            case R.id.layout_add_attention://加关注
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                AnimationUtil.AlphaScaleAnimator(layout_add_attention, new AnimatorListener() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        if (layout_add_attention != null) {
                            layout_add_attention.animate().alpha(1).scaleX(1).scaleY(1);
                        }
                    }
                });
                EventBus.getDefault().post(new AddAttention());
                break;
        }
    }

    /**
     * 显示输入框弹窗
     */
    private InputNoteDialog getInputDialog() {
        inputNoteDialog = InputNoteDialog.getInstance(mContent, mReplyContent, authorDetailBeanMap);
        inputNoteDialog
                .setOnDialogInputListener(new InputNoteDialog.OnDialogInputListener() {
                    @Override
                    public void sendCommentSuccess(LinkedHashMap<String, AuthorDetailBean> map, String content) {
                        EventBus.getDefault().post(new PostComment(content, map));
                    }

                    @Override
                    public void dimiss(LinkedHashMap<String, AuthorDetailBean> map, String content, String replyContent) {
                        inputNoteDialog.dismissDialog();
                        inputNoteDialog = null;
                        authorDetailBeanMap = map;
                        mContent = content;
                        mReplyContent = replyContent;
                    }
                });
        return inputNoteDialog;
    }

    @Override
    public void onScrolled(int direction, int distance) {
        if (StretchPager.STRETCH_LEFT == direction) {
            int status = (Math.abs(distance) > Distance) ? 1 : 0;
            if (status != lastStatus) {
                TextView tvTips = leftView.findViewById(R.id.tv_tips);
                ImageView ivPull = leftView.findViewById(R.id.iv_pull);
                tvTips.setText(status == 0 ? "右拉刷新" : "释放刷新");
                if (0 == status && 1 == lastStatus) {
                    ivPull.startAnimation(animLeftEnd);
                } else if (1 == status) {
                    ivPull.startAnimation(animLeftStart);
                }
            }
            lastStatus = status;
        } else if (StretchPager.STRETCH_RIGHT == direction) {
            int status = (Math.abs(distance) > Distance) ? 1 : 0;
            if (status != lastStatus) {
                TextView tv_tips = rightView.findViewById(R.id.tv_tips);
                ImageView ivPull = rightView.findViewById(R.id.iv_pull);
                tv_tips.setText(status == 0 ? "左拉加载" : isLoadAll ? "已加载全部" : "释放加载");
                if (0 == status && 1 == lastStatus) {
                    ivPull.startAnimation(animRightEnd);
                } else if (1 == status) {
                    ivPull.startAnimation(animRightStart);
                }
            }
            lastStatus = status;
        }
    }

    @Override
    public void onRefresh(int direction, int distance) {
        this.direction = direction;
        if (StretchPager.STRETCH_LEFT == direction) {
            if (distance >= Distance) {
                pageIndex = 1;
                getAtricleDetails();
            }
        } else if (StretchPager.STRETCH_RIGHT == direction) {
            if (distance >= Distance) {
                if (!isLoadAll) {
                    pageIndex++;
                    getAtricleDetails();
                }
            }
        }
    }

    @Override
    public void onRelease(int direction) {
        lastStatus = 0;
        if (StretchPager.STRETCH_LEFT == direction) {
            TextView tvTips = leftView.findViewById(R.id.tv_tips);
            ImageView ivPull = leftView.findViewById(R.id.iv_pull);
            ivPull.clearAnimation();
            tvTips.setText("右拉刷新");
        } else {
            TextView tvTips = rightView.findViewById(R.id.tv_tips);
            ImageView ivPull = rightView.findViewById(R.id.iv_pull);
            ivPull.clearAnimation();
            tvTips.setText("左拉加载");
        }
    }

    /**
     * 文章详情
     *
     * @param responseBeanList
     */
    @Override
    public void onArticleDetail(List<ArticleItem> responseBeanList) {
        if (mArticleDetailsPagerAdapter != null) {
            if (direction == StretchPager.STRETCH_RIGHT) {
                isLoadAll = false;
                if (responseBeanList.size() < pageSize) {
                    isLoadAll = true;
                }
                this.mArticleItemList.addAll(responseBeanList);
                mArticleDetailsPagerAdapter.setResponseBeanList(mArticleItemList);
                mArticleDetailsPagerAdapter.notifyDataSetChanged(false);
            } else {
                if (pageIndex == 1) {
                    showLoading(false);
                    toast("已为你推荐更多新内容");
                }
                isLoadAll = false;
                this.mArticleItemList = responseBeanList;
                mArticleDetailsPagerAdapter.setResponseBeanList(mArticleItemList);
                mArticleDetailsPagerAdapter.notifyDataSetChanged(true);
                currentPosition = 0;
                recordCurrentArticle();
            }
        }
    }

    /**
     * 获取文章属性
     *
     * @param attribute
     */
    @Override
    public void onArticleAttribute(ArticleAttribute attribute) {
        if (attribute == null) {
            return;
        }
        ArticleAttribute.ResponseBean bean = attribute.getResponse();
        if (bean == null) {
            return;
        }
        this.attribute = bean;
        updateArticleAttribute();
//        if (BuildConfig.IS_DEBUG) {
//            if (bean != null && articleItem != null) {
//                int heat = articleItem.getHeatCount();
//                final boolean isLike = bean.getIsLike() == 0 ? false : true;
//                if (heat >= 500 && !isLike) {
//                    isManualLike = true;
//                    getLike();
//                }
//            }
//        }
    }

    /**
     * 离开文章时填写对文章的行为记录
     *
     * @param bean
     */
    @Override
    public void onUserBehavior(INetBean bean) {

    }

    /**
     * 浏览
     *
     * @param bean
     */
    @Override
    public void onBrowseArticle(INetBean bean) {
        if (articleItem == null) {
            return;
        }
        articleItem.setBrowse(true);
    }

    /**
     * 获取是否收藏
     *
     * @param userCollect
     */
    @Override
    public void onIsConcern(UserCollect userCollect) {
        if (userCollect.getErrCode() == 0) {
            UserCollect.ResponseBean bean = userCollect.getResponse();
            this.articleItem.setIsCollect(bean.getIsShouChang());
        }
    }

    /**
     * 收藏
     *
     * @param iNetBean
     */
    @Override
    public void onIsCollect(INetBean iNetBean) {
        if (iNetBean.getErrCode() == 0) {
            if (iNetBean.getErrMsg().equals("收藏成功")) {
                this.articleItem.setIsCollect(1);
                toast("已收藏，可至个人中心查看我收藏的");
            } else {
                this.articleItem.setIsCollect(0);
                toast("取消收藏成功");
            }
        }
    }


    /**
     * 点赞，取消点赞
     *
     * @param articleLike
     * @param isLike
     */
    @Override
    public void onArticleLikeOrOffLike(ArticleLike articleLike, boolean isLike) {
        if (articleLike != null) {
            if (articleLike.getErrCode() == 0) {
                if (attribute == null) {
                    return;
                }
                int likeCount = attribute.getLikeCount();
                likeCount = isLike ? likeCount + 1 : likeCount <= 0 ? 0 : likeCount - 1;
                attribute.setLikeCount(likeCount);
                attribute.setIsLike(isLike ? 1 : 0);
                //更新点赞
                setIv_like(isLike, likeCount);
            } else {
                toast(articleLike.getErrMsg());
            }
        }
    }


    /**
     * 屏幕单击，滑动事件处理
     *
     * @param screenEvent
     */
    @Subscribe
    public void receiveScreenEvent(ReceiverScreenEvent screenEvent) {
        mScrollY = screenEvent.getScrollY();
        mTitleLocation = screenEvent.getTitle_location();
        int head_location = screenEvent.getHead_location();
        int commentLocation = screenEvent.getCommtentLocation();
        //是否出现在最顶部
        isScrollTheTop = mScrollY == 0;
        //是否滑动到了评论
        isScrollToComment = mScrollY >= commentLocation;
        //是否显示关注
        isShowAttention = mScrollY > head_location;
        //修改toolbar背景
        boolean isWhiteBg = TextUtils.isEmpty(articleItem.getTopImg()) ? true : false;
        replaceToolbarrResource(isWhiteBg);
    }

    /**
     * 评论区增加，删除，更新评论数
     */
    @Subscribe
    public void updateCommentCount(UpdateCommmentCount updateCommmentCount) {
        if (updateCommmentCount == null || attribute == null) {
            return;
        }
        boolean isAddComment = updateCommmentCount.isAddComment();
        int count = attribute.getCommentCount();
        count = isAddComment ? count + 1 : count <= 0 ? 0 : count - 1;
        attribute.setCommentCount(count);
        setCommentCount(count);
    }

    /**
     * 评论或则回复成功后，关闭并清空dialog输入框信息
     */
    @Subscribe
    public void cleanKeyBoard(CleanKeyBoard keyBoard) {
        if (keyBoard == null) {
            return;
        }
        inputNoteDialog.dismissDialog();
    }

    /**
     * 回复或则回复回复，设置dialog输入框提示信息
     */
    @Subscribe
    public void setInputHint(SetInput input) {
        if (input == null) {
            return;
        }
        mReplyContent = input.getReplyContent();
        getInputDialog().show(getSupportFragmentManager(), InputNoteDialog.class.getSimpleName());
    }

    /**
     * 关注状态请求
     */
    @Subscribe
    public void onAttentionStateChange(AttentionStateChange stateChange) {
        if (articleItem == null || stateChange == null) {
            return;
        }
        articleItem.setIsConcern(stateChange.getIsConcern());
        if (layout_add_attention != null) {
            layout_add_attention.setVisibility(articleItem.getUser_id() == getUserId() ?
                    View.GONE : articleItem.getIsConcern() > 0 ?
                    View.GONE : isShowAttention ? View.VISIBLE : View.GONE);//0没有关注，1已关注
        }
        if (stateChange.isOtherHomePagerReturn()) {
            getIsShouChang();
        }
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        App.getApplication().setList(mArticleItemList);
        intent.putExtra(Constant.INTENT_PAGEINDEX, pageIndex);
        setResult(RESULT_OK, intent);
        super.onBackPressed();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_LOGIN://登录界面返回
                    EventBus.getDefault().post(new AddAttention());
                    //获取文章属性
                    getArticleAttribute();
                    //获取我是否收藏
                    getIsShouChang();
                    //统计阅读
                    getbrowse();
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
